<template>
  <div class="app-container">
    <el-card class="tree-container" shadow="hover">

      <el-input
        v-model="filterText"
        placeholder="输入关键字进行过滤"
      />
    </el-card>

    <el-card class="tree-container" shadow="hover">
      <el-tree
        ref="tree"
        v-loading="treeLoading"
        :data="menuTreeList"
        default-expand-all
        :filter-node-method="filterNode"
        node-key="id"
        accordion
      >
        <span slot-scope="{ node, data }" class="tree-node">
          <el-badge :value="data.sort">

            <el-tag type="text">{{ node.label }}</el-tag>
          </el-badge>
          <span>
            <el-button
              type="primary"
              size="mini"
              @click.stop="() => component(data.id)"
            >
              组件
            </el-button>
            <el-button
              type="warning"
              size="mini"
              @click.stop="() => updateApi(data)"
            >
              API
            </el-button>
            <el-button
              type="success"
              size="mini"
              @click.stop="() => update(data)"
            >
              修改
            </el-button>
            <el-button
              type="info"
              size="mini"
              @click.stop="() => append(data)"
            >
              增加
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click.stop="() => remove(node, data)"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
      <div style="margin-top: 20px" align="center">
        <el-button type="primary" @click="handleSave()">保存</el-button>
        <el-button @click="handleClear()">清空</el-button>
      </div>

    </el-card>

    <el-dialog
      :title="isAdd ? '新增菜单' : '编辑菜单' "
      :visible.sync="updateMenuFormVisible"
      center
      width="30%"
    >
      <el-form
        ref="updateMenuForm"
        :rules="updateMenuRules"
        :model="updateMenuForm"
      >
        <el-form-item v-show="isAdd" label="父菜单：">
          <el-input v-model="parentName" disabled />
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input v-model="updateMenuForm.name" />
        </el-form-item>
        <el-form-item label="Permission：" prop="code">
          <el-input v-model="updateMenuForm.code" />
        </el-form-item>
        <el-form-item label="排序：" prop="sort">
          <el-input-number v-model="updateMenuForm.sort" :min="1" />
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="updateMenuFormVisible = false">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="handleSaveMenu">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

import {
  getTree,
  create,
  updateById,
  deleteById
} from '@/api/system/menu'

const defaulMenuForm = {
  sort: 1
}

export default {
  data() {
    return {
      menuTreeList: [],

      updateMenuForm: {},
      updateMenuFormVisible: false,
      statusOptions: [{
        value: 1,
        label: '启用'
      }, {
        value: 0,
        label: '禁用'
      }],
      filterText: '',
      parentName: null,
      isAdd: false,
      // 当前新增、修改的菜单
      currentTreeNode: null,
      updateMenuRules: {
        name: [{ required: true, trigger: 'blur', message: '请填写名称' }],
        sort: [{ required: true, trigger: 'blur', message: '请填写排序' }],
        code: [{ required: true, trigger: 'blur', message: '请填写Permission' }]
      },

      loading: false,
      treeLoading: true

    }
  },
  created() {
    this.getTree()
  },
  methods: {
    getTree() {
      this.treeLoading = true
      getTree().then(response => {
        const data = response.data
        this.menuTreeList = data
        this.treeLoading = false
      })
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    append(data) {
      this.currentTreeNode = data
      this.parentName = data.label
      this.isAdd = true
      this.updateMenuForm = Object.assign({}, defaulMenuForm)
      this.updateMenuForm.parentId = data.id
      this.updateMenuFormVisible = true
    },
    update(data) {
      this.currentTreeNode = data
      this.parentName = data.label
      this.isAdd = false

      const { label, code, sort } = data
      this.updateMenuForm = {
        name: label,
        code,
        sort
      }
      this.updateMenuFormVisible = true
    },

    handleSaveMenu() {
      this.$refs.updateMenuForm.validate(valid => {
        if (valid) {
          this.$confirm('确认保存菜单？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            if (this.isAdd) {
              create(this.updateMenuForm).then(res => {
                this.$message.success('新增菜单成功！')
                this.updateMenuFormVisible = false

                // 不刷新数据，js拼接
                const { id, name, code, sort } = res.data
                const newChild = {
                  id,
                  label: name,
                  code,
                  sort
                }

                const currentTreeNode = this.currentTreeNode
                if (!currentTreeNode.children) {
                  this.$set(currentTreeNode, 'children', [])
                }
                currentTreeNode.children.push(newChild)
              })
            } else {
              updateById(this.currentTreeNode.id, this.updateMenuForm).then(_ => {
                this.$message.success('修改菜单成功！')
                this.updateMenuFormVisible = false

                this.currentTreeNode = Object.assign({}, this.updateMenuForm)
                this.currentTreeNode.label = name
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    remove(node, data) {
      const parent = node.parent
      this.$confirm(`是否删除'${data.label}'菜单及其子菜单?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById(data.id).then(() => {
          const children = parent.data.children || parent.data
          const index = children.findIndex(d => d.id === data.id)
          children.splice(index, 1)
        })
      })
    },
    component(menuPermissionId) {
      this.$router.push({
        path: '/system/permission/component',
        query: {
          menuPermissionId
        }
      })
    },
    updateApi(row) {
      this.$router.push({
        path: '/system/permission/api-alloc',
        query: {
          id: row.id,
          uiType: 0
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;

  .el-badge__content.is-fixed{
    right:0px!important
  }
}

</style>
